﻿using System;
using System.Windows;
using System.Windows.Threading;
using DevExpress.Xpf.Core;
using Loki.UI.Wpf.Resources;

namespace Loki.UI.Wpf
{
    public class WpfBootStrapper<TMainViewModelType> : BootStrapper where TMainViewModelType : class, IViewModel
    {
        protected BootStrapperAdapter<TMainViewModelType> BootStrapper { get; private set; }

        public WpfBootStrapper()
        {
            Startup += new StartupEventHandler(BootStrapperWPF_Startup);

            BootStrapper = new BootStrapperAdapter<TMainViewModelType>(this);
            BootStrapper.Initializing += BootStrapper_Initializing;
            BootStrapper.Initialized += BootStrapper_Initialized;

            DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(BootStrapper_DispatcherUnhandledException);
        }

        private void BootStrapper_Initialized(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(ThemeName))
            {
                ThemeManager.ApplicationThemeName = ThemeName;
            }

            var L_SkinURI = new Uri(SKIN_RESOURCE_NAME);
            var L_ResourcesURI = new Uri(WPF_RESROUCE_NAME);
            var L_BusyIndicatorURI = new Uri(BUSY_INDICATOR_RESROUCE_NAME);

            Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = L_SkinURI });
            Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = L_ResourcesURI });
            Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = L_BusyIndicatorURI });
        }

        private void BootStrapper_Initializing(object sender, EventArgs e)
        {
            Log.Info(LogStrings.BootStrapper_Intialize);
        }

        private void BootStrapper_DispatcherUnhandledException(object P_Sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            OnLastChanceError(new ExceptionEventArgs(e.Exception));
            e.Handled = true;
        }

        private void BootStrapperWPF_Startup(object P_Sender, StartupEventArgs e)
        {
            BootStrapper.Initialize();
        }

        private const string SKIN_RESOURCE_NAME = "pack://application:,,,/Loki.UI.Wpf;component/Resources/LokiSkin.xaml";
        private const string WPF_RESROUCE_NAME = "pack://application:,,,/Loki.UI.Wpf;component/Resources/LokiResources.xaml";

        private const string BUSY_INDICATOR_RESROUCE_NAME = "pack://application:,,,/Loki.UI.Wpf;component/Controls/BusyIndicator/Template.xaml";
    }
}